#!/usr/bin/python
import logging
from flask import Flask, render_template, jsonify, make_response
import os.path

from nmj.updater import NMJUpdater
from nmj.abstract import MediaFile


_LOGGER = logging.getLogger(__name__)
#BASE_DIR="/home/ecolleu/dev/nmjv2/movie_test"
BASE_DIR="/mnt/nas/videos/films"
app = Flask(__name__)

@app.route('/')
def home():
	return render_template('home.html')

@app.route('/movies')
def get_movies():
	result = []
	updater = NMJUpdater(BASE_DIR, "local_directory")
	for media in updater.get_shows():
		result.append(media.export())
	_LOGGER.info("get_movies result : %s", result)
	return jsonify(movies = sorted(result, key=lambda movie: movie["search_title"]))

@app.route('/movie/details/nmj_database/media/video/poster/<poster_filename>')
@app.route('/nmj_database/media/video/poster/<poster_filename>')
def get_poster(poster_filename):
	resp = make_response(open(os.path.join(BASE_DIR, "nmj_database/media/video/poster", poster_filename)).read())
	resp.content_type = "image/jpeg"
	return resp

@app.route('/movie/details/<movie_id>')
def get_movie(movie_id):
	updater = NMJUpdater(BASE_DIR, "local_directory")
	show = updater.get_show(show_id=movie_id)
	_LOGGER.debug("show json: %s", show.jsondetails())
	return render_template("details.html", **show.jsondetails())

@app.route('/movie/details/<movie_id>/research')
def research(movie_id):
	return render_template("search_movies.html", id=movie_id)

@app.route('/movie/details/<movie_id>/movies')
def research_movie(movie_id):
	result = {}
	updater = NMJUpdater(BASE_DIR, "local_directory")
	video = updater.get_video(show_id=movie_id)
	for media in updater.search(video.basename):
		result.update(media.export())
	return jsonify(**result)

@app.route('/about')
def about():
	return render_template('about.html')

if __name__ == "__main__":
	logging.basicConfig(level=logging.DEBUG)
	app.run(debug=True, host="0.0.0.0", port=5000)
